import { getCurrentUserId } from '@/utils/backend/auth'
import { prisma } from '@/utils/backend/db'
import { HttpStatus } from '@/utils/httpStatus'
import { NextResponse } from 'next/server'

export async function GET(req: Request) {
  try {
    const { searchParams } = new URL(req.url)
    const page = Number(searchParams.get('page')) || 1
    const pageSize = Number(searchParams.get('pageSize')) || 10
    const keyword = searchParams.get('keyword') || ''
    const token = req.headers.get('Authorization')?.replace('Bearer ', '')!
    const userId = await getCurrentUserId(token)
    if (!userId) {
      return NextResponse.json(
        {
          success: false,
          message: '未授权'
        },
        { status: HttpStatus.UNAUTHORIZED }
      )
    }

    // 查询条件：查找已接受的好友请求
    const where = {
      OR: [
        {
          senderId: userId,
          status: 'accepted',
          receiver: {
            OR: [{ username: { contains: keyword } }, { nickname: { contains: keyword } }]
          }
        },
        {
          receiverId: userId,
          status: 'accepted',
          sender: {
            OR: [{ username: { contains: keyword } }, { nickname: { contains: keyword } }]
          }
        }
      ]
    }

    // 查询总数
    const total = await prisma.friend.count({ where })

    // 查询好友列表
    const friends = await prisma.friend.findMany({
      where,
      include: {
        sender: {
          select: {
            id: true,
            username: true,
            nickname: true,
            gender: true,
            avatar: true,
            status: true
          }
        },
        receiver: {
          select: {
            id: true,
            username: true,
            nickname: true,
            gender: true,
            avatar: true,
            status: true
          }
        }
      },
      skip: (page - 1) * pageSize,
      take: pageSize,
      orderBy: {
        createdAt: 'desc'
      }
    })

    // 处理返回数据格式
    const friendList = friends.map(friend => {
      const friendInfo = friend.senderId === userId ? friend.receiver : friend.sender
      return {
        id: friendInfo.id,
        username: friendInfo.username,
        nickname: friendInfo.nickname,
        gender: friendInfo.gender,
        avatar: friendInfo.avatar,
        status: friendInfo.status,
        createdAt: friend.createdAt
      }
    })

    return NextResponse.json({
      success: true,
      message: '获取成功',
      data: {
        list: friendList,
        pagination: {
          current: page,
          pageSize,
          total
        }
      }
    })
  } catch (error) {
    console.error('获取好友列表失败:', error)
    return NextResponse.json(
      {
        success: false,
        message: '获取好友列表失败'
      },
      { status: HttpStatus.INTERNAL_SERVER_ERROR }
    )
  }
}
